#include <bits/stdc++.h>

using namespace std;

// 有重复项数组的去重全排列
// 测试链接 : https://leetcode.cn/problems/permutations-ii/

class Solution 
{
private:
    vector<vector<int>> ret;

    void f(vector<int>& nums, int i)
    {
        if(i == nums.size())
        {
            ret.emplace_back(nums);
            return;
        }
        
        unordered_set<int> s;
        for(int j = i; j < nums.size(); ++j)
        {
            if(!s.count(nums[j]))
            {
                s.insert(nums[j]);
                swap(nums[i], nums[j]);
                f(nums, i + 1);
                swap(nums[i], nums[j]);
            }
        }
    }

public:
    vector<vector<int>> permuteUnique(vector<int>& nums) 
    {
        sort(nums.begin(), nums.end());
        f(nums, 0);
        return ret;
    }
};



class Solution 
{
private:
    vector<vector<int>> ret;
    vector<int> path;
    bool visited[9];

    void dfs(const vector<int>& nums)
    {
        if(path.size() == nums.size())
        {
            ret.push_back(path);
            return;
        }

        for(int i = 0; i < nums.size(); ++i)
        {
            if(visited[i] == false && (i == 0 || nums[i] != nums[i - 1] || visited[i - 1] == true))
            {
                path.push_back(nums[i]);
                visited[i] = true;
                dfs(nums);
                path.pop_back();
                visited[i] = false;
            }
        }
    }

public:
    vector<vector<int>> permuteUnique(vector<int>& nums) 
    {
        sort(nums.begin(), nums.end());
        dfs(nums);
        return ret;
    }
};